package com.jxb.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.reactive.ReactorLoadBalancerExchangeFilterFunction;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;

import reactor.core.publisher.Mono;

/**
 * 类注释
 *
 * @author jiaobo
 * @date Created in 2024/10/5 20:16
 **/
@RestController
public class RibbonAndLoadBalancerController {

    // @Autowired
    // private RestTemplate restTemplate;

    @Autowired
    private WebClient webClient;

    @RequestMapping(value = "/findOrderByUserId/{id}")
    public Mono<Object> findOrderByUserId(@PathVariable("id") Integer id) {
        // ribbon实现，restTemplate需要添加@LoadBalanced注解
        String url = "http://mall-order/findOrderByUserId/"+id;
        // Object result = restTemplate.getForObject(url,Object.class);
        Mono<Object> objectMono = webClient.get().uri(url).retrieve().bodyToMono(Object.class);

        return objectMono;
    }

    @Autowired
    private ReactorLoadBalancerExchangeFilterFunction lbFunction;

    @RequestMapping(value = "/findOrderByUserId3/{id}")
    public Mono<Object> findOrderByUserIdWithWebFlux(@PathVariable("id") Integer id) {

        String url = "http://mall-order/findOrderByUserId/"+id;
        //基于WebClient+webFlux
        Mono<Object> result = WebClient.builder()
                .filter(lbFunction)
                .build()
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(Object.class);
        return result;
    }

}
